﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace SyncService.Core
{
    public class PushDataMiddle : AssetSyncServiceBase
    {
        private IMemoryCache? _cache = null;
        private ILogger<PushDataMiddle> _logger = null;

        public Dictionary<int, string> FormName = new Dictionary<int, string>()
        {
            { 48,"报废自定义表单"},
            { 49,"调拨自定义表单"},
            { 50,"发票登记自定义表单"},
            { 51,"盘点自定义表单"},
            { 57,"0元列管入库单"},
             { 59,"批量调拨单"},
             { 60,"V测试资产调拨单"}
        };
        public PushDataMiddle(string from, string to, string? notifies)
            : base(YdConstants.YIDEA, "Esb", "")
        { }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _cache = Resolver.Resolve<IMemoryCache>();
            _logger = Resolver.Resolve<ILogger<PushDataMiddle>>();
        }
        public AssetSyncEvent? Data { get; set; }

        public string SerialNo => Data!.Data!["SerialNo"]!.ToString();

        public string CreatedById => Data!.Data!["CreatedBy"]!.ToString();

        public int SourceType { get; set; }

        public bool IsUpdatePushResponse => (SourceType == 51||SourceType==52 || SourceType == 55) ? false : true;
        protected Employee GetEmployeeById() {
            QueryParam queryParam = new QueryParam();
            queryParam.FilterString = "id=" + CreatedById;

            List<Employee> employees = FromClient.GetEmployees(queryParam).ToList();
            if (employees.Count > 0)
            {
                return employees[0];

            }
            return new Employee();
        }

        protected string GetExtendFieldValue(string field) {
            try
            {
                var Field = ExtendFields.First(x => x.ObjectType == SourceType && x.Name == field);
                var value = Data!.Data?[Field.FieldId]?.ToString();
                return value??"";
            }
            catch (Exception ex) {
                _logger.LogError("查找ExtendFieldValue fail:"+SourceType+","+field, ex);
                return "";
            }
        }

        private List<AssetType> GetAssetTypeFromCache() {
            _cache.TryGetValue("AssetType", out var assetValue);
            List<AssetType> assetTypeList = new List<AssetType>();
            if (assetValue != null)
            {
                assetTypeList = ((IEnumerable<dynamic>)assetValue).Select(item => new AssetType
                {
                    Id = item.Id,
                    Name = item.Name,
                    Hierarchy = item.Hierarchy,
                    Code = item.Code
                }).ToList();
            }
            else
            {
                assetTypeList = FromClient.GetAssetTypes(null).ToList();
                _cache.Set("AssetType", assetTypeList, DateTime.Now.AddMinutes(5));
            }
            return assetTypeList;
        }
        protected AssetType GetTopAssetTypeById(int index=0) {

            List < AssetType > assetTypeList=GetAssetTypeFromCache();
            string assetTypeCode = "";
            var assetTypeValue = GetExtendFieldValue("资产分类");
            if (assetTypeValue.ToString().StartsWith("["))
            {
                JsonArray assetTypeArray = (JsonArray)(JsonNode.Parse( assetTypeValue));
                assetTypeCode = assetTypeArray[0]["value"].ToString();
            }
            else
            {
                assetTypeCode = JsonNode.Parse(GetExtendFieldValue("资产分类"))!["value"]!.ToString();
            }
            var assetType = assetTypeList.Where(e => e.Code == assetTypeCode).FirstOrDefault();
            var hierarchy = assetType.Hierarchy.Split('|');
            string hierarchyId = "";
            if (hierarchy.Length > index)
            {
                hierarchyId = hierarchy[index];
            }
            else {
                hierarchyId = hierarchy[0];
            }
            int topAssetTypeId = 0;
            int.TryParse(hierarchyId, out topAssetTypeId);
            var topAssetType = assetTypeList.Where(e => e.Id == topAssetTypeId).FirstOrDefault();

            return topAssetType;
            
        }
        /// <summary>
        /// 更新主单据推送状态等
        /// </summary>
        /// <param name="serialNo"></param>
        /// <param name="sourceType"></param>
        /// <param name="response"></param>
        protected void UpdateMainPushResponse(JsonObject response)
        {
            if (IsUpdatePushResponse)
            {
                //单据子单据
                var assetClearForm = UserDefines.First(x => x.Name == FormName[SourceType]);
                CustomizedFormData customizedFormData = new CustomizedFormData();
                customizedFormData.FormId = assetClearForm.Id;
                customizedFormData.WebhookPush = false;
                customizedFormData.SerialNo = SerialNo;
                JsonObject customizedData = new JsonObject();
                var pushStateField = ExtendFields.First(x => x.ObjectType == SourceType && x.Name == "推送状态");
                JsonObject stateValue = new JsonObject();
                stateValue.Add("value", response["code"].ToString());
                customizedData.Add(pushStateField.FieldId, stateValue);
                var pushReasonField = ExtendFields.First(x => x.ObjectType == SourceType && x.Name == "失败原因");
                JsonObject reasonValue = new JsonObject();
                reasonValue.Add("value", response["message"].ToString());
                customizedData.Add(pushReasonField.FieldId, reasonValue);
                if (response["code"].ToString() == "000000")
                {
                    var procInstIdField = ExtendFields.First(x => x.ObjectType == SourceType && x.Name == "procInstId");
                    var procInstIdValue = new JsonObject
                    {
                        ["value"] = response["result"].ToString()
                    };
                    customizedData.Add(procInstIdField.FieldId, procInstIdValue);
                }

                customizedFormData.Data = customizedData;
                string jsonString = JsonSerializer.Serialize(customizedFormData);
                _logger.LogInformation("更新主单据推送数据：" + jsonString);
                var updateResponse = FromClient.UpdateCustomizedFormData(customizedFormData, null);
                _logger.LogInformation("更新主单据推送状态:" + updateResponse);
            }

        }

        /// <summary>
        /// 添加自定义推送状态记录表
        /// </summary>
        /// <param name="serialNo"></param>
        /// <param name="state"></param>
        /// <param name="result"></param>
        protected void AddPushRecord(int state, string result)
        {
            var customForm = UserDefines.First(x => x.Name == "单据状态记录");
            CustomizedFormData customizedFormData1 = new CustomizedFormData();
            customizedFormData1.StartWorkflow = false;
            customizedFormData1.TriggerRobot = false;
            customizedFormData1.FormId = customForm.Id;
            var billField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "billno");
            var procInstIdDefalutField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "procInstId");
            var stateField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "state");
            customizedFormData1.Data = new JsonObject
            {
                [billField.FieldId] = new JsonObject
                {
                    ["value"] = SerialNo.ToString()
                },
                [procInstIdDefalutField.FieldId] = new JsonObject
                {
                    ["value"] = result
                },
                [stateField.FieldId] = new JsonObject
                {
                    ["value"] = state
                }
            };
            bool addResult= FromClient.AddNewCustomizedFormData(customizedFormData1);
            _logger.LogInformation("添加自定义推送状态记录表状态:" + addResult);
        }

        public override void ExecuteCore()
        {
            throw new NotImplementedException();
        }
    }
}
